package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.common.utils.JSONUtils;
import com.hunttown.mes.manage.service.TransportTableChineseEnglishDetailManageService;
import com.hunttown.mes.manage.service.TransportTableChineseEnglishManageService;
import com.hunttown.mes.rpc.domain.TransportTableChineseEnglishDTO;
import com.hunttown.mes.rpc.domain.TransportTableChineseEnglishDetailDTO;
import com.hunttown.mes.rpc.domain.query.TransportTableChineseEnglishDetailDTOQuery;
import com.hunttown.common.domain.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 中英文对照表 字段
 * @author: wangjunfu
 * @date: 2019-08-14 10:34:46
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/datatable-detail")
public class TableChineseEnglishDetailController {

    private final static Logger logger = LoggerFactory.getLogger(TableChineseEnglishDetailController.class);

    private final TransportTableChineseEnglishManageService chineseEnglishService;
    private final TransportTableChineseEnglishDetailManageService englishDetailService;

    @Autowired
    public TableChineseEnglishDetailController(TransportTableChineseEnglishManageService chineseEnglishService, TransportTableChineseEnglishDetailManageService englishDetailService) {
        this.englishDetailService = englishDetailService;
        this.chineseEnglishService = chineseEnglishService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, TransportTableChineseEnglishDetailDTOQuery dtoQuery) {

        if (dtoQuery.getTableId() == null || dtoQuery.getTableId() < 0) {
            throw new RuntimeException("未查询到数据库表信息");
        }

        Page<TransportTableChineseEnglishDetailDTO> dataPage = englishDetailService.getForPage(dtoQuery);

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        TransportTableChineseEnglishDTO englishDTO = chineseEnglishService.getById(dtoQuery.getTableId());
        model.addAttribute("englishObj", englishDTO);

        return "basic/datatable-detail/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id, Integer tableId) {
        if (tableId == null || tableId < 0) {
            throw new RuntimeException("未查询到数据库表信息");
        }

        //主表信息
        TransportTableChineseEnglishDTO englishDTO = chineseEnglishService.getById(tableId);
        model.addAttribute("englishObj", englishDTO);

        //数据结构信息
        id = (id == null ? 0 : id);
        TransportTableChineseEnglishDetailDTO obj = new TransportTableChineseEnglishDetailDTO();
        obj.setId(id);

        if (id > 0) {
            obj = englishDetailService.getById(id);
        }
        model.addAttribute("Obj", obj);

        return "basic/datatable-detail/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportTableChineseEnglishDetailDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            //新增时检验是否唯一
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                TransportTableChineseEnglishDetailDTOQuery query = new TransportTableChineseEnglishDetailDTOQuery();
                query.setTableId(objDTO.getTableId());
                query.setFieldName(objDTO.getFieldName());
                TransportTableChineseEnglishDetailDTO obj = englishDetailService.getByQuery(query);

                if (obj != null && obj.getId() > 0) {
                    //说明此记录已经存在，不能重复插入
                    map = OperateCode.CompositionResult(map, -10, "此字段已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO = englishDetailService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                objDTO.setFieldName(null);
                Boolean isNext = englishDetailService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = englishDetailService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = englishDetailService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

}